<?php
/*
Auth:Sang
Desc:表单数据验证类
Date:2014-11-01
*/
namespace Lib;
class Validator{
  protected $data=array(),$error,$rules=array(),$messages=array();
  
  public function __construct($data){
    $this->setData($data);
  }
  public function setData($data){
    if($data){
      $this->data=$data;
    }
    return $this;
  }
  
  public function setRules($rules){
    if(!empty($rules)){
      $this->rules=$rules;
    }
    return $this;
  }
  
  public function setMessages($messages){
    if(!empty($messages)){
      $this->messages=$messages;
    }
    return $this;
  }
  
  public function getError(){
    return $this->error;
  }
  
  public function validate(){
    if(!$this->data){
      return false;
    }
    
    if(!$this->rules){
      return $this->data;
    }
    $data=array();
    foreach($this->rules as $key=>$rules){
      if(isset($rules['required'])){
        $rule=$rules['required'];
        if(((function_exists($rule) && $rule()===true) || $rule===true) && (!isset($this->data[$key]) || $this->data[$key]===null || $this->data[$key]==='')){
          $this->setError($key, 'required');
          return false;
        }
        unset($rules['required']);
      }elseif(!isset($this->data[$key])){
        continue;
      }
      if(empty($rules)){
        $data[$key]=$this->data[$key];
        continue;
      }
      foreach($rules as $rule_name=>$rule){
        if(!empty($rule)){
          if(strpos($rule,',')!==false){
            $rule=explode(',',$rule);
          }else{
            $rule=(array)$rule;
          }
        }else{
          $data[$key]=$this->data[$key];
          continue;
        }
        foreach($rule as $r){
          if(isset($this->data[$key]) && $this->data[$key]!=='' && $this->data[$key]!==null){
            if(!empty($r) && ($value=$r($this->data[$key]))===false){
              $this->setError($key, $rule_name);
              return false;
            }else{
              $this->data[$key]=$value;
              $data[$key]=$value;
            }
          }else{
            $data[$key]=$this->data[$key];
          }
        }
      }
    }
    return $data;
  }
  
  protected function setError($key,$rule){
    if(!$this->messages[$key][$rule]){
      $this->error='no such field:'.$key;
    }else{
      $this->error=$this->messages[$key][$rule];
    }
  }
}